/**
 * 文件名：****.java
 * 版权：Copyright Lightkit All Rights Reserved.
 * 描述：*****
 */
package com.lightkits.wms.domain.nontaskpickinglist.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.db.entity.FndEventTypeBase;
import com.lightkits.common.db.entity.FndOrganizationBase;
import com.lightkits.common.db.entity.WmRequestHeader;
import com.lightkits.common.db.entity.WmRequestLine;
import com.lightkits.common.db.entity.event.BdEvent;
import com.lightkits.common.db.entity.event.BdEventRecord;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.model.CheckResult;
import com.lightkits.framework.common.utility.date.DateUtil;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.object.ParseUtil;
import com.lightkits.framework.soa.client.id.GetGlobalIDRequestType;
import com.lightkits.framework.soa.client.id.GetGlobalIDResponseType;
import com.lightkits.framework.soa.client.id.IDServiceClient;
import com.lightkits.wms.client.DocumentServiceClient;
import com.lightkits.wms.domain.deliveryorder.service.CreateDeliveryOrderDomain;
import com.lightkits.wms.domain.nontaskpickinglist.service.CreateNonTaskPickParams;
import com.lightkits.wms.domain.usuallyinterface.GetWmMoveTypeExecutor;
import com.lightkits.wms.dto.document.GenerateDocNumRequestType;
import com.lightkits.wms.dto.document.GenerateDocNumResponseType;
import com.lightkits.wms.dto.nontaskpicking.model.PickingHeaderDTO;
import com.lightkits.wms.dto.nontaskpicking.model.PickingLineDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * CreateNonTaskPickParams
 *
 * @author jing.wei@hand-china.com
 * Created on 2019/5/9 14:41
 */
@Service
public class CreateNonTaskPickParamsimpl implements CreateNonTaskPickParams {
    private final Logger logger = LoggerFactory.getLogger(GetWmMoveTypeExecutor.class);

    private final IDServiceClient idAdapterService;
    private final DocumentServiceClient client;

    @Autowired
    public CreateNonTaskPickParamsimpl(IDServiceClient idAdapterService,
                                       DocumentServiceClient client) {
        this.idAdapterService = idAdapterService;
        this.client = client;
    }

    /**
     * 创建事件
     *
     * @param headerDTO 领料单头参数
     * @return BdEvent
     */
    @Override
    public CheckResult<BdEvent> createEvent(PickingHeaderDTO headerDTO) {
        CheckResult<BdEvent> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        GetGlobalIDRequestType idRequest = new GetGlobalIDRequestType();
        idRequest.setCount(1);
        GetGlobalIDResponseType idResponse = idAdapterService.getGlobalId(idRequest);
        Iterator<Long> sfIds = idResponse.getIds().iterator();
        BdEvent event = new BdEvent();
        event.setEventTypeCode("WM_REQUEST_NEW");
        FndEventTypeBase eventTypeBase = new FndEventTypeBase()
                .selectOne(new EntityWrapper()
                        .eq(FndEventTypeBase.EVENT_TYPE_CODE, "WM_REQUEST_NEW"));
        event.setEventTypeId(eventTypeBase.getId());
        event.setEventRequestId(sfIds.next());
        event.setOrganizationId(ParseUtil.tryLongWithException(headerDTO.getOrgId()));
        if (!ObjectUtil.isNullOrEmpty(headerDTO.getWorkcellId())) {
            event.setWorkcellId(ParseUtil.tryLongWithException(headerDTO.getWorkcellId()));
        }
        if (!ObjectUtil.isNullOrEmpty(headerDTO.getProdlineId())) {
            event.setProdLineId(ParseUtil.tryLongWithException(headerDTO.getProdlineId()));
        }
        if (!ObjectUtil.isNullOrEmpty(headerDTO.getRequestWorkerId())) {
            event.setWorkerId(ParseUtil.tryLongWithException(headerDTO.getRequestWorkerId()));
        }
        //create EventRecord

        List<BdEventRecord> bdEventRecords = new ArrayList<>();
        BdEventRecord record = this.createRecord("WM_REQUEST", new Long(0), null, null);
        bdEventRecords.add(record);

        event.store(bdEventRecords);
        checkResult.setData(event);
        return checkResult;
    }

    /**
     * 创建快照
     *
     * @param objectType 事件对象类型
     * @param keyValue   事件关键值
     * @param objectId   事件对象ID
     * @param recordType 事件记录类型
     * @return BdEventRecord
     */
    private BdEventRecord createRecord(String objectType, Long objectId, String keyValue, String recordType) {
        BdEventRecord record = new BdEventRecord();
        record.setObjectId(objectId);
        record.setKeyValue(keyValue);
        record.setObjectType(objectType);
        record.setRecordType(recordType);
        return record;
    }

    /**
     * 创建领料单头
     *
     * @param dto 领料单头参数
     * @return WmRequestHeader
     */
    @Override
    public CheckResult<WmRequestHeader> createRequestHeader(PickingHeaderDTO dto) {
        CheckResult<WmRequestHeader> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        WmRequestHeader header = new WmRequestHeader();
        GenerateDocNumRequestType request = new GenerateDocNumRequestType();
        request.setCount(1);
        request.setSize(5);
        request.setType("WR");
        request.setField1(df.format(new Date()));
        GenerateDocNumResponseType response = client.generateDocNumber(request);
        header.setRequestNum(response.getDocNumList().get(0));
        header.setOrganizationId(ParseUtil.tryLongWithException(dto.getOrgId()));
        header.setOperationType(dto.getOperationType());
        FndOrganizationBase base = new FndOrganizationBase().selectById(dto.getOrgId());
        header.setEnterpriseId(base.getParentOrganizationId());
        FndOrganizationBase base2 = new FndOrganizationBase().selectById(dto.getToOrganzationId());
        if (base2 != null) {
            header.setToEnterpriseId(base2.getParentOrganizationId());
        }
        try {
            header.setPlanDemandDate(DateUtil.toDate(dto.getDemandDate(), DateUtil.DEFAULT_DATETIME_PATTERN));
        } catch (Exception e) {
            throw new LightKitsBizException("时间格式异常");
        }
        header.setCreatorId(ParseUtil.tryLongWithException(dto.getCreatorId()));
        header.setProcessStatus("NEW");
        header.setRequestType(dto.getRequestType());
        header.setRemark(dto.getRemark());
        if (!ObjectUtil.isNullOrEmpty(dto.getMoId())) {
            header.setMoId(ParseUtil.tryLongWithException(dto.getMoId()));
        }
        if (!ObjectUtil.isNullOrEmpty(dto.getRequestWorkerId())) {
            header.setRequestWorkerId(ParseUtil.tryLongWithException(dto.getRequestWorkerId()));
        }
        if (!ObjectUtil.isNullOrEmpty(dto.getProdlineId())) {
            header.setProdLineId(ParseUtil.tryLongWithException(dto.getProdlineId()));
        }
        if (!ObjectUtil.isNullOrEmpty(dto.getWorkcellId())) {
            header.setWorkcellId(ParseUtil.tryLongWithException(dto.getWorkcellId()));
        }
        if (!ObjectUtil.isNullOrEmpty(dto.getToOrganzationId())) {
            header.setToOrganizationId(ParseUtil.tryLongWithException(dto.getToOrganzationId()));
        }
        checkResult.setData(header);
        return checkResult;
    }

    /**
     * 创建领料单行
     *
     * @param lineDTOS 领料单行参数
     * @param headerId 领料单头Id
     * @return WmRequestLine
     */
    @Override
    public CheckResult<List<WmRequestLine>> createRequestLines(List<PickingLineDTO> lineDTOS, Long headerId) {
        CheckResult<List<WmRequestLine>> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        List<WmRequestLine> lines = new ArrayList<>();
        int num = 10;
        for (PickingLineDTO dto : lineDTOS) {
            WmRequestLine line = new WmRequestLine();
            line.setRequestId(headerId);
            line.setApplyQty(new BigDecimal(dto.getApplyQty()));
            line.setLineNum(new Long(num));
            line.setUom(dto.getUomCode());
            line.setLineStatus("NEW");
            num += 10;
            line.setItemId(ParseUtil.tryLongWithException(dto.getItemId()));
            line.setRemark(dto.getRemark());
            line.setOwnerType("OWN");
            line.setSourceType(dto.getSourceType());
            line.setWarehouseId(ParseUtil.tryLongWithException(dto.getFromWarehouseId()));
            if (!ObjectUtil.isNullOrEmpty(dto.getFromAreaId())) {
                line.setWmAreaId(ParseUtil.tryLongWithException(dto.getFromAreaId()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getFromWorkcellId())) {
                line.setWorkcellId(ParseUtil.tryLongWithException(dto.getFromWorkcellId()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getToWarehouseId())) {
                line.setToWarehouseId(ParseUtil.tryLongWithException(dto.getToWarehouseId()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getToAreaId())) {
                line.setToWmAreaId(ParseUtil.tryLongWithException(dto.getToAreaId()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getToWorkcellId())) {
                line.setToWorkcellId(ParseUtil.tryLongWithException(dto.getToWorkcellId()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getSourceId())) {
                line.setSourceId(ParseUtil.tryLongWithException(dto.getSourceId()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getSourceLineId())) {
                line.setSourceLineId(ParseUtil.tryLongWithException(dto.getSourceLineId()));
            }
            lines.add(line);
        }
        checkResult.setData(lines);

        return checkResult;
    }

}
